package cn.demon.system.service.impl;

import cn.demon.system.domain.Role;
import cn.demon.system.mapper.RoleMapper;
import cn.demon.system.service.IRoleService;
import cn.demon.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional
    public void del(Long id) {
        //删除中间表数据
        roleMapper.delRoleMenuByRoleId(id);
        roleMapper.delRolePermissionByRoleId(id);
        roleMapper.delEmployeeRoleByRoleId(id);
        //有外键关联 - 先删除关联数据 - 再删主表数据
        super.del(id);
    }

    /**
     * 添加
     * @param role
     */
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addData(role);
    }

    /**
     * 修改
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
        //先删除旧权限
        roleMapper.delRoleMenuByRoleId(role.getId());
        roleMapper.delRolePermissionByRoleId(role.getId());
        //再添加新的权限
        addData(role);
        super.update(role);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void patchDelete(Long[] ids) {
        for (Long id : ids) {
            del(id);
        }
    }

    // 抽取公共代码
    private void addData(Role role) {
        ArrayList<Long> menus = role.getMenus();

        if (menus.size() > 0) {
            roleMapper.addRoleMenu(role.getId(), menus);
        }

        ArrayList<Long> permissions = role.getPermissions();

        if (permissions.size() > 0) {
            roleMapper.addRolePermission(role.getId(), permissions);
        }
    }
}
